-- gameSeverNoticeModel
-- 游戏服务器公告.

local gameSeverNoticeModel = {}

gameSeverNoticeModel._gameSeverNoticeList = {} -- 经过过滤需要弹出的公告列表
gameSeverNoticeModel._lastModifyTimeStamp = nil -- 上次修改的时间戳
gameSeverNoticeModel._hadShownListED = nil -- 每天首次登录弹出公告 已弹出的列表
gameSeverNoticeModel._hadShownListSlot = nil -- 一段时间之内弹出公告 已弹出的列表
gameSeverNoticeModel._curtime = nil -- 解析数据时的服务器时间

gameSeverNoticeModel._isLoginedNoticeHasGot = false -- 是否已经获取过登录后公告

-- 拉取游戏服务器公告
function gameSeverNoticeModel:requestGameSeverNoticeList()
	app.session:request("pb_server.C2S_NoticeList", {})
end

function gameSeverNoticeModel:parseLoginNoticeData()
	self._lastModifyTimeStamp = UD.setting:getLastModifyTStampOfEveryDayLogin() -- 上次修改的时间戳
	self._curtime = app:getTime()

	if 0 == self._lastModifyTimeStamp then -- 没记录过值、应该只有新建账号才会=0
		self._hadShownListED = {}
		self._hadShownListSlot = {}
	else
		if os.date("%Y.%m.%d", self._lastModifyTimeStamp) == os.date("%Y.%m.%d", self._curtime) then -- 同一天之内
			local hadShownListED = UD.setting:getEveryDayLoginIdList() -- 每天首次登录弹出公告 已弹出的列表
			if "" ~= hadShownListED then
				self._hadShownListED = string.split( hadShownListED, ";" )
			else
				self._hadShownListED = {}
			end
		else --跨天
			self._hadShownListED = {}
		end

		self._hadShownListSlot = {}
		local hadShownListSlot = UD.setting:getOneTimeInSlot() -- 一段时间之内弹出公告 已弹出的列表
		if "" ~= hadShownListSlot then
			local hadShownListSlotTemp = string.split( hadShownListSlot, ";" )
			for _,v in pairs( hadShownListSlotTemp ) do
				local temp = string.split( v, "," )
				if tonumber( temp[2] ) > self._curtime then -- 记录没过期、(已过期的不记录，不会写回去，则不会导致字段内容不限增大 ）
					table.insert( self._hadShownListSlot, temp )
				end
			end
		end
	end
end

-- 解析公告数据
function gameSeverNoticeModel:setGameSeverNoticeList( ret )
    if ret and #ret.list > 0  then -- 有公告内容
	    self._rollNoticeList = {}
        self._gameSeverNoticeList = {}

        for _,v in ipairs( ret.list ) do
			local eachContentTemp = {
				title = v.title or "",
				titleType = v.titleType or 0, -- 灭有就是0
				content = v.content or "",
				priority = v.priority or 0,
				buttonName = v.buttonName or "",
				buttonUrl = v.buttonUrl or "",
				id = v.id or "",
				type = v.type or 0,
				beginTime = v.beginTime or 0,
				endTime = v.endTime or 0
			}

        	if 1 == v.type then -- 每次登录都需要弹
	            table.insert( self._gameSeverNoticeList, eachContentTemp )
	        elseif 2 == v.type then -- 每天第一次登录弹
	        	if not table.indexof( self._hadShownListED, v.id ) then -- 没弹出过了
	        		table.insert( self._gameSeverNoticeList, eachContentTemp )
	        	end
	        elseif 3 == v.type then -- 有效时间之内只弹一次
	        	local haveShown = false -- 显示过？默认没有
	        	for i,v2 in pairs( self._hadShownListSlot ) do
	        		if v2[1] == v.id then
	        			haveShown = true -- 在显示过的列表中
	        		end
	        	end
	        	if not haveShown and eachContentTemp.endTime >= self._curtime then -- 没显示过、且处于有效期内。则需要弹出
	        		table.insert( self._gameSeverNoticeList, eachContentTemp )
	        	end
	        elseif 4 == v.type then -- 普通跑马灯
	        	if #v.content > 0 then
		        	self._rollNoticeList[#self._rollNoticeList + 1] = {content = v.content, priority = 999} -- 普通跑马灯优先级最低
				end
			elseif 5 == v.type then -- 订制跑马灯
				if #v.content > 0 then
					local tempInfo = {}
					local strTemp, message -- 发到聊天系统的格式化文本(str为可点击部分，message为拼接后的文本)
					local ret = string.split(v.content, ";")
					if ret then
						local marqueeConf = GD:getMarqueeConfigById(tonumber(ret[1]))
						if tonumber(ret[1]) == 1001 or tonumber(ret[1]) == 1004 then
							-- 十连抽获得的奖励需要根据品质修改颜色(坐骑或者道具)
							local retTemp = string.split(ret[3], "|")
							local loottype = tonumber(retTemp[1])
							local lootid = tonumber(retTemp[2])
							local itemData = UD:parseLootToBagItem({type = loottype, id = lootid, num = 1})							
							local name = itemData and L(itemData:getName())
							local quality = itemData and itemData:getQuality()
							local colorStr = display.stringWithColor(Enums.QualityColor[quality])
							local contentTemp = display.getRichTextFontXml(name, colorStr)
							tempInfo.content = string.format(L(marqueeConf.content), ret[2], contentTemp)
							if loottype == 1 then -- 道具
								strTemp = "[i|"..name.."|"..lootid.."|"..quality.."]"
							elseif loottype == 4 then -- 坐骑							
								strTemp = "[m|"..name.."|"..lootid.."|"..quality.."]"
							end
							message = string.format(L(marqueeConf.content), ret[2], strTemp)  
						elseif tonumber(ret[1]) == 1002 then
							-- 冠军赛
							local throneConf = GD:queryThroneByDay(tonumber(ret[3]))
							local name = throneConf and L(throneConf.name) or tonumber(ret[3])
							tempInfo.content = string.format(L(marqueeConf.content), ret[2], name)
							message = tempInfo.content
						else
							tempInfo.content = string.format(L(marqueeConf.content), ret[2], ret[3])
							message = tempInfo.content
						end						
						tempInfo.priority = tonumber(marqueeConf.priotity)
						self._rollNoticeList[#self._rollNoticeList + 1] = tempInfo

						--发送一条系统消息
						if tonumber(marqueeConf.systemNotice) == 1 then							
							app:sendMsg("IMModel", "addSystemMsg", message)
						end
					end
				end
			end
		end

		table.sort(self._gameSeverNoticeList, function(a, b)
			if a == b then
				return true
			else
				return a.priority < b.priority
			end
		end)
    end

    if self._gameSeverNoticeList then
		-- 数据存回ud.setting
		self._lastModifyTimeStamp = app:getTime()
		UD.setting:setLastModifyTStampOfEveryDayLogin( self._lastModifyTimeStamp )

		for k,v in pairs( self._gameSeverNoticeList ) do
			if 2 == v.type then
				table.insert( self._hadShownListED, v.id )
			elseif 3 == v.type then
				local temp = { v.id, tostring( v.endTime ) }
				table.insert( self._hadShownListSlot, temp )
			end
		end
		local tempStr = table.concat( self._hadShownListED, ";" )
		UD.setting:setEveryDayLoginIdList( tempStr )

		local str = ""
		local showListSlotCount = #self._hadShownListSlot
		for i = 1, showListSlotCount do
			local itemTemp  = self._hadShownListSlot[i]
			local tempStr2 = table.concat( itemTemp, "," )
			str = str .. tempStr2
			if i < showListSlotCount then
				str = str .. ";"
			end
		end
		UD.setting:setOneTimeInSlot( str )
		UD.dirty = true
	end
end

function gameSeverNoticeModel:getRollNoticeList()
	local ret = self._rollNoticeList
	self._rollNoticeList = nil
	return ret
end

function gameSeverNoticeModel:getGameSeverNoticeList()
	return self._gameSeverNoticeList
end

function gameSeverNoticeModel:_parseTencentNotice(content)
	local noticeList = {}
	if type(content)=="string" and #content > 0 then
		local noticeStr = string.nl2br(content)
		noticeStr = string.restorehtmlspecialchars(noticeStr)
		local noticeAry = string.split(noticeStr, "{|}")
		for i,v in ipairs(noticeAry) do
		    if #v > 0 then
		        local ary = string.split(v, "|")
		        local notice = {
			        title = ary[1],
			        titleType = -1,
			        content = ary[3],
			        priority = -1,
			        buttonName = "",
			        buttonUrl = ""
			    }

			    if 1 == tonumber( ary[2] ) then -- 文本
			        notice.titleType = 0
			    elseif 2 == tonumber( ary[2] ) then -- 本地pic path
			        notice.titleType = 2
			    end

		        table.insert( noticeList, notice )
		    end
		end
	end

	-- print("parseTencentNotice", content)
	-- dump(noticeList, "noticeList")

	return noticeList
end

function gameSeverNoticeModel:getLoginNoticeList()
	local content = app.channelAPI:getLoginNotice()
	-- content = "登录前公告1|1|这是登录前公告{|}登录前公告2|1|这个是登录前公告"
	return self:_parseTencentNotice(content)
end

function gameSeverNoticeModel:getLoginedNoticeList()
	if self._isLoginedNoticeHasGot then return {} end
	self._isLoginedNoticeHasGot = true

	local content = app.channelAPI:getLoginedNotice()
	-- content = "登录后公告1|1|这是登录后公告{|}登录后公告2|1|这个是登录后公告"
	return self:_parseTencentNotice(content)
end

function gameSeverNoticeModel:_getLoginZoneNoticeList()
	local content = app.channelAPI:getLoginZoneNotice()
	-- content = "区服测试|1|##3~5#2#6##这是区服测试公告{|}区服测试|1|这个是区服测试公告，会被抛弃"
	local noticeList = self:_parseTencentNotice(content)
	local zoneNoticeDict = {}

	local function addZoneNotice(zoneId, notice)
		if not zoneId then return end
		zoneNoticeDict[zoneId] = zoneNoticeDict[zoneId] or {}
		table.insert(zoneNoticeDict[zoneId], notice)
	end

	local ary, sub_ary
	for i,notice in ipairs(noticeList) do
		content = notice.content
		local startIdx, endIdx, zoneStr = string.find(content, "##([~#0-9]+)##")
		if startIdx then
			content = string.sub(content, endIdx + 1)
			if #content > 0 then
				notice.content = content
				ary = string.split(zoneStr, "#")
				for j,v in ipairs(ary) do
					if string.isContain(v, "~") then
						sub_ary = table.tonumber(string.split(v, "~"))
						if sub_ary[1] and sub_ary[2] and sub_ary[1] <= sub_ary[2] then
							for k=sub_ary[1],sub_ary[2] do
								addZoneNotice(k, notice)
							end
						end
					else
						addZoneNotice(tonumber(v), notice)
					end
				end
			end
		end
	end

	-- dump(zoneNoticeDict, "zoneNoticeDict", 10)
	return zoneNoticeDict
end

function gameSeverNoticeModel:getLoginZoneNoticeById(zoneId)
	local noticeListDict = self:_getLoginZoneNoticeList()
	return noticeListDict[zoneId]
end

return gameSeverNoticeModel